package com.zzk.lanouhn.myapplication1.fragments;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.zzk.lanouhn.myapplication1.R;
import com.zzk.lanouhn.myapplication1.adapters.InvestOneAdapter;
import com.zzk.lanouhn.myapplication1.adapters.TestNormalAdaptert;
import com.zzk.lanouhn.myapplication1.modles.InvestOneLunBoModle;
import com.zzk.lanouhn.myapplication1.modles.InvestOneModle;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by lanouhn on 16/8/23.
 */
public class InvestOneFragment extends Fragment {
    private XRecyclerView recyclerView;

    private InvestOneAdapter investOneAdapter;

    //下面为轮播图的设置
    private InvestOneLunBoModle lunBoModle;
    private TestNormalAdaptert adaptert;
    private RollPagerView rollPagerView;

    private int page = 1;
    //真实加载的
    private List<InvestOneModle.DataBean> mList = new ArrayList<>();
    //中间值
    private List<InvestOneModle.DataBean> tempList = new ArrayList<>();


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_invest_one, null);

        //下拉刷新和上拉加载
        recyclerView = (XRecyclerView) view.findViewById(R.id.invest_one_recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

        //上拉加载的动画效果
        recyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        //recyclerView.setLaodingMoreProgressStyle(ProgressStyle.Pacman);
        //下拉刷新的动画效果
        recyclerView.setArrowImageView(R.drawable.ic_loading_rotate);

        recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            //下拉刷新
            @Override
            public void onRefresh() {
                page = 1;
                getDataInvestOne();
            }

            //上拉加载
            @Override
            public void onLoadMore() {
                page++;
                getDataInvestOne();
            }
        });

        //使焦点不在recycleView
        //recyclerView.setFocusable(false);
        //轮播图的设置
        rollPagerView = new RollPagerView(getActivity());
        rollPagerView.setPlayDelay(3000);
        rollPagerView.setAnimationDurtion(500);

        LinearLayout.LayoutParams imagebtn_params = new LinearLayout.LayoutParams(

                LinearLayout.LayoutParams.WRAP_CONTENT, 250);
        rollPagerView.setLayoutParams(imagebtn_params);

        rollPagerView.setHintView(new ColorPointHintView(getActivity(), Color.YELLOW, Color.WHITE));
        recyclerView.addHeaderView(rollPagerView);


        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(llm);

        getDataInvestOne();
        getDataLunBo();
        return view;
    }


    private void getDataInvestOne() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String s = Integer.toString(page);
                String url = "http://lol.zhangyoubao.com/apis/rest/ItemsService/lists?cattype=news&catid=" +
                        "10178&page=" + s + "&i_=EAC1B788-00BC-454A-A9B9-460852CFC011&t_=1438745347&p_=18386&v_=" +
                        "40050303&d_=ios&osv_=8.3&version=0&a_=lol";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(url).build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendEmptyMessage(0);

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        Gson gson = new Gson();

                        tempList = gson.fromJson(result, InvestOneModle.class).getData();

                        if (tempList.size() > 0) {
                            handler.sendEmptyMessage(1);
                        } else {
                            handler.sendEmptyMessage(2);
                        }
                    }
                });
            }
        }).start();

    }

    //轮播
    private void getDataLunBo() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String urlLunbo = "http://lol.zhangyoubao.com/apis/rest/ItemsService/ads?&i_=EAC1B788-" +
                        "00BC-454A-A9B9-460852CFC011&t_=1438744725&p_=16520&v_=40050303&d_=ios&osv_=" +
                        "8.3&version=0&a_=lol";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(urlLunbo).build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Toast.makeText(getActivity(), "失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        Gson gson = new Gson();
                        lunBoModle = gson.fromJson(result, InvestOneLunBoModle.class);
                        if (lunBoModle.getData().size() > 0) {
                            handler.sendEmptyMessage(3);
                        } else {
                            handler.sendEmptyMessage(4);
                        }
                    }
                });
            }
        }).start();
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

                case 0:
                    Toast.makeText(getActivity(), "失败", Toast.LENGTH_SHORT).show();
                    recyclerView.refreshComplete();
                    recyclerView.loadMoreComplete();
                    break;
                case 1:
                    if (page == 1) {
                        mList.clear();
                        mList.addAll(tempList);
                        //获取适配器
                        investOneAdapter = new InvestOneAdapter(getActivity(), mList);
                        //绑定适配器
                        recyclerView.setAdapter(investOneAdapter);

                        recyclerView.refreshComplete();
                        tempList.clear();
                    } else {
                        mList.addAll(tempList);
                        investOneAdapter.notifyDataSetChanged();
                        recyclerView.loadMoreComplete();
                        tempList.clear();
                    }
                    //绑定点击事件
                    //investOneAdapter.setInvestOneOnltemClickLisener(InvestOneFragment.this);
                    break;
                case 3:
                    //获取适配器，就是实例化适配器
                    adaptert = new TestNormalAdaptert(getActivity(), lunBoModle);
                    rollPagerView.setAdapter(adaptert);
                    break;
                case 2:
                    Toast.makeText(getActivity(), "失败", Toast.LENGTH_SHORT).show();
                    break;
                case 4:
                    Toast.makeText(getActivity(), "失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

//    @Override
//    public void investOneOntemClick(String position) {
//        Intent intent = new Intent(getActivity(), InvestOneDetailed.class);
//        intent.putExtra("posi", position);
//        startActivity(intent);
//    }
}
